package com.example.crypt;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;

/**
 * DES加密解密类,负责byte数组的加解密
 *
 * @author wzq
 * @2014年5月4日
 */
/* package */
public class TypeDes implements IByteCrypt {
    private static final String DES_KEY = "DesEncrypt";
    private Cipher encryptCipher = null;// 加密
    private Cipher decryptCipher = null;// 解密

    /**
     * 构造函数，出声相关数据
     */
    public TypeDes() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
            sr.setSeed(DES_KEY.getBytes());
            keyGenerator.init(sr);
            Key key = keyGenerator.generateKey();
            encryptCipher = Cipher.getInstance("DES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, key);
            decryptCipher = Cipher.getInstance("DES");
            decryptCipher.init(Cipher.DECRYPT_MODE, key);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("Error initializing DESEncrypt");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            throw new RuntimeException("Error initializing DESEncrypt");
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            throw new RuntimeException("Error initializing DESEncrypt");
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            throw new RuntimeException("Error initializing DESEncrypt");
        }
    }

    /**
     * 加密byte[]
     *
     * @param src
     * @return
     */
    public byte[] encryptBytes(byte[] src) {
        try {
            return encryptCipher.doFinal(src);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密byte[]
     *
     * @param src
     * @return
     */
    public byte[] decryptBytes(byte[] src) {
        try {
            return decryptCipher.doFinal(src);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
